package com.woniu51.finance.service;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.woniu51.finance.config.AlipayConfig;
import com.woniu51.order.api.OrderFeignClient;
import com.woniu51.order.domain.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * @author 杨光
 * @date 2022年04月11日 15:57
 */
@Service
public class FinanceService {

    @Autowired
    private OrderFeignClient orderFeignClient;

    @Value("${alipay.callback.ip}")
    private String ip;

    @Value("${alipay.callback.port}")
    private String port;

    public String pay(Long orderId){
        Integer payAmount = 0;
        //远程调用order service，获取订单信息
        Order order = orderFeignClient.queryByOrderId(orderId);
        payAmount = order.getOrderTotalPay();

        //1.获取订单提交的参数(并处理中文乱码)
        //1.1 商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = orderId+"";
        //1.2 付款金额，必填
        String total_amount = payAmount+"";
        //1.3订单名称，必填
        String subject = "电影票";
        //1.4商品描述，可空
        String body = "电影票";
        //2. 获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        //2.1设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl("http://"+ip+":"+port+"/alipay/notify");
        alipayRequest.setNotifyUrl("http://"+ip+":"+port+"/alipay/notify");

        //2.2 将商户的信息全部封装到访问沙箱的请求中
        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        try {
            //3. 向支付宝沙箱发送请求，并接受响应的支付页面源码
            String result = alipayClient.pageExecute(alipayRequest).getBody();
            return result;
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return "fail";
    }

    public Integer confirmPay(Long oid) {
        orderFeignClient.confirmPay(oid);
        return null;
    }
}
